<!-- 时间对象 -->
<template>
    <div class="dashboard-editor-container">
        <el-row style="background: #fff; padding: 16px 16px ;">
            <div >
                <el-button class="btn" type="primary" @click="addDepartment()" >添加对象</el-button>
            </div>
            <div>
                <el-table 
                border 
                :data="tableData" 
                style="width: 100%; margin: 15px 0" 
                row-key="ID"  
                default-expand-all 
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                <el-table-column prop="date" type="index" label="序号" width="80" align="left"></el-table-column>
                <el-table-column prop="Name" label="对象名称" width="180"></el-table-column>
                <el-table-column prop="TimeType" label="时间类型" width="180">
                  <template slot-scope="scope">
                    <span>{{scope.row.TimeType === 1 ? '循环时间' : '单次时间'}}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="RecuringDays" label="定义详情" >
                  <template slot-scope="scope">
                    <span v-show="scope.row.RecuringDays != []" v-for="item in scope.row.RecuringDays" :key="item">
                      <span v-if="item===1">星期一  </span>
                      <span v-if="item===2">星期二  </span>
                      <span v-if="item===3">星期三  </span>
                      <span v-if="item===4">星期四  </span>
                      <span v-if="item===5">星期五  </span>
                      <span v-if="item===6">星期六  </span>
                      <span v-if="item===7">星期天  </span>
                    </span>
                    <span v-for="(item,index) in scope.row.RecuringTimes" :key="index">{{ item.Start+" ~ "+ item.End + '； '}}</span>
                    <!-- {{scope.row.RecuringDays}} -->
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="left" width="150px">
                    <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.row)">修改</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
                </el-table>
            </div>
            </el-row>
            <el-dialog :close-on-press-escape='false' top="3%" title="时间对象" :visible.sync="dialogVisible" @close='closeDialog' :close-on-click-modal = false  v-el-drag-dialog width="60%">
                <el-form label-width="25%" :model="ruleForm" :rules="rules" ref="ruleForm">
                    <el-form-item label='对象名：' prop="Detail.Name">
                        <el-input :disabled='ruleForm.Action===2' v-model="ruleForm.Detail.Name" size="small"></el-input>
                    </el-form-item>
                    <el-form-item label='类型：'>
                        <el-radio-group v-model="ruleForm.Detail.TimeType" @change="radioChange">
                          <el-radio :label="2">单次时间</el-radio>
                          <el-radio :label="1">循环时间</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label='日期：' prop="Detail.RecuringDays" v-if="ruleForm.Detail.TimeType===1">
                        <el-select v-model="ruleForm.Detail.RecuringDays"  size="small" multiple placeholder="请选择日期">
                          <el-option
                            v-for="item in dateOption"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label='时间：' prop="Detail.RecuringTimes">
                      <div style="width:70%;">
                        <el-button size="small" type="primary" style="float:right;margin-bottom:10px;" @click='innerVisible=true'>添加</el-button>
                      </div>
                      <el-table border :data="ruleForm.Detail.RecuringTimes" style="width: 70%; margin: 15px 0" >
                        <el-table-column prop="Start" label="开始时间"></el-table-column>
                        <el-table-column prop="End" label="结束时间" ></el-table-column>
                        <el-table-column label="操作" align="left" width="150px">
                            <template slot-scope="scope">
                            <el-button size="mini" @click="dateEdit(scope.row)">修改</el-button>
                            <el-button size="mini" type="danger" @click="dateDelete(scope.$index,ruleForm.Detail.RecuringTimes)">删除</el-button>
                            </template>
                        </el-table-column>
                      </el-table>
                    </el-form-item>
                    <el-dialog width="30%"  :close-on-press-escape='false' :close-on-click-modal ='false' v-el-drag-dialog title="选择时间" top="10%" :visible.sync="innerVisible" @close='dateRuleClose' append-to-body>
                      <el-form label-width="30%" :model="dateForm" :rules="dateRule" ref="dateForm">
                        <el-form-item label='开始时间：' prop="Start2" v-if="ruleForm.Detail.TimeType===2" :rules="ruleForm.Detail.TimeType===2? dateRule.Start2:[]">
                          <el-date-picker size="small" :picker-options="pickerOptionsStart" v-model="dateForm.Start2"  value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请选择开始时间"></el-date-picker>
                        </el-form-item>
                        <el-form-item label='结束时间：' prop="End2" v-if="ruleForm.Detail.TimeType===2" :rules="ruleForm.Detail.TimeType===2? dateRule.End2:[]">
                          <el-date-picker size="small" :picker-options="pickerOptionsEnd" v-model="dateForm.End2" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请选择结束时间"></el-date-picker>
                        </el-form-item>
                        <el-form-item label='开始时间：' prop="Start" v-if="ruleForm.Detail.TimeType===1" :rules="ruleForm.Detail.TimeType===1? dateRule.Start:[]">
                          <el-time-picker size="small" v-model="dateForm.Start" value-format="HH:mm:ss" format="HH:mm:ss"  placeholder="请选择开始时间"></el-time-picker>
                        </el-form-item>
                        <el-form-item label='结束时间：' prop="End" v-if="ruleForm.Detail.TimeType===1" :rules="ruleForm.Detail.TimeType===2? dateRule.End:[]">
                          <el-time-picker size="small" value-format="HH:mm:ss" format="HH:mm:ss"  v-model="dateForm.End"  placeholder="请选择结束时间"></el-time-picker>
                        </el-form-item>
                      </el-form>
                      <span slot="footer" class="dialog-footer">
                        <el-button @click="innerVisible = false">取 消</el-button>
                        <el-button type="primary" @click="timeClick('dateForm')">确 定</el-button>
                      </span>
                    </el-dialog>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submit()">{{ruleForm.Action===1?'确 定':'保 存'}}</el-button>
                </span>
            </el-dialog>
    </div>
</template>

<script>
import { deepClone } from '@/utils'
import { connrequest } from "@/api/firstPage";
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  directives: { elDragDialog },
  data() {
    
    return {
      dialogVisible: false,
      ruleForm:{
        Action:1,
        Detail:{
          Name:'',
          TimeType:2,
          RecuringDays:[],
          RecuringTimes:[]
        }
      },
      cloneForm:{},
      dateForm:{
        Start:'00:00:00',
        Start2:'',
        End:'23:59:59',
        End2:''
      },
      innerVisible:false,
      Datetable:[],
      dateOption:[
        {label:'星期一',value:1},
        {label:'星期二',value:2},
        {label:'星期三',value:3},
        {label:'星期四',value:4},
        {label:'星期五',value:5},
        {label:'星期六',value:6},
        {label:'星期天',value:7},
      ],
      // 配置开始时间不能大于结束时间
      pickerOptionsStart: {
        disabledDate: time => {
          if (this.dateForm.End2) {
            return time.getTime() > new Date(this.dateForm.End2).getTime();
          }
        }
      },
      pickerOptionsEnd: {
        disabledDate: time => {
          if (this.dateForm.Start2) {
            return time.getTime() < new Date(this.dateForm.Start2).getTime() - 86000000;  //86400000
          }
        }
      },
      tableData: [],
      cloneOnce:[],//存放单次时间
      cloneloop:[],//存放循环时间
      rules:{
        'Detail.Name':[{required: true, message: '对象名不能为空',trigger:"blur"}],
        'Detail.RecuringDays':[{required: true, message: '请选择日期',trigger:"change"}],
        'Detail.RecuringTimes':[{required: true, message: '时间列表不能为空',trigger:"blur"}],
        departName: [
          { required: true, message: '部门名称不能为空' }
        ],
      },
      dateRule:{
        Start:[{required: true, message: '请选择开始时间',trigger:"change"}],
        End:[{required: true, message: '请选择结束时间',trigger:"change"}],
        Start2:[{required: true, message: '请选择开始时间',trigger:"change"}],
        End2:[{required: true, message: '请选择结束时间',trigger:"change"}],
      }
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
    this.dateForm.Start2 = this.getNowDate() + ' ' + '00:00:00'
    this.dateForm.End2 = this.getNowDate() + ' ' + '23:59:59'
    this.cloneForm = deepClone(this.ruleForm)
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  methods: {
    getNowDate() {
      const timeOne = new Date()
      const year = timeOne.getFullYear()
      let month = timeOne.getMonth() + 1
      let day = timeOne.getDate()
      month = month < 10 ? '0' + month : month
      day = day < 10 ? '0' + day : day
      const NOW_MONTHS_AGO = `${year}-${month}-${day}`
      return NOW_MONTHS_AGO
    },
    async getData(){
      const res = await connrequest('GetSchedule')
      this.tableData = res.Data
    },
    async Schedule(message){
      // this.ruleForm.Action = Action;
      const data = {
        Data:this.ruleForm
      }
      const res = await connrequest('EditSchedule',data);
      if (res.Status.StatusCode === 0) {
        this.getData();
        this.$message.success(message);
        this.dialogVisible = false;
      }
    },
    // 添加日期
    timeClick(){
      // this.cloneloop = []
      // console.log(this.cloneOnce);
      this.$refs['dateForm'].validate( async(valid) => {
        if(valid){
          if (this.ruleForm.Detail.TimeType===2) {
            if (this.ruleForm.Detail.RecuringTimes.length != 0) {
              let exist = false;
              this.ruleForm.Detail.RecuringTimes.map(item=>{
                if (item.End === this.dateForm.End2 && item.Start === this.dateForm.Start2) {
                  exist = true
                  this.$message.error('重复数据,请重新录入')
                  return
                }
              })
              if(!exist){
                this.cloneOnce.push(deepClone({Start:this.dateForm.Start2,End:this.dateForm.End2}));
                this.ruleForm.Detail.RecuringTimes = deepClone(this.cloneOnce);
              }
            }else{
              this.cloneOnce.push(deepClone({Start:this.dateForm.Start2,End:this.dateForm.End2}));
              this.ruleForm.Detail.RecuringTimes = deepClone(this.cloneOnce);
            }
          }else{
            if (this.ruleForm.Detail.RecuringTimes.length != 0) {
              let exist = false;
              this.ruleForm.Detail.RecuringTimes.map(item=>{
                if (item.End === this.dateForm.End && item.Start === this.dateForm.Start) {
                  exist = true
                  this.$message.error('重复数据,请重新录入')
                  return
                }
              })
              if(!exist){
                  this.cloneloop.push(deepClone({Start:this.dateForm.Start,End:this.dateForm.End})); //将填选的值克隆给存放数据的数组
                  this.ruleForm.Detail.RecuringTimes = deepClone(this.cloneloop);
                }
            }else{
              this.cloneloop.push(deepClone({Start:this.dateForm.Start,End:this.dateForm.End})); //将填选的值克隆给存放数据的数组
              this.ruleForm.Detail.RecuringTimes = deepClone(this.cloneloop);
            }
          }
          // this.$message.success('添加成功');
          this.innerVisible = false;
        }
      })
    },
    addDepartment(){
      this.ruleForm.Action = 1;
      this.ruleForm = deepClone(this.cloneForm)
      this.dialogVisible = true;
    },
    // 修改主列表
    handleEdit(item){
      // console.log(item);
      this.cloneOnce = []
      this.cloneloop = []
      this.ruleForm.Action = 2;
      this.dialogVisible = true;
      this.ruleForm.Detail = deepClone(item);
      if (this.ruleForm.Detail.TimeType===2) {
        this.cloneOnce = deepClone(this.ruleForm.Detail.RecuringTimes);
      } else {
        this.cloneloop = deepClone(this.ruleForm.Detail.RecuringTimes);
      }
      
      console.log(this.cloneOnce,this.cloneloop);
    },
    // 修改二级列表
    dateEdit(row){
      this.innerVisible = true;
      if (this.ruleForm.Detail.TimeType===2) {
        this.dateForm.Start2 = row.Start;
        this.dateForm.End2 = row.End;
      }else{
        this.dateForm = {...row}
      }
    },
    // 删除二级列表数据
    dateDelete(index,rows){
      rows.splice(index,1)
    },
    radioChange(val){
      this.dateForm.Start = '00:00:00';
      this.dateForm.End = '23:59:59';
      this.dateForm.Start2 = this.getNowDate() + ' ' + '00:00:00'
      this.dateForm.End2 = this.getNowDate() + ' ' + '23:59:59'
      if (val===2) {
        this.ruleForm.Detail.RecuringTimes = deepClone(this.cloneOnce);
      }else{
        this.ruleForm.Detail.RecuringTimes = deepClone(this.cloneloop);
      }
    },
    async submit(){
      this.$refs['ruleForm'].validate( async(valid) => {
        if(valid){
          if (this.ruleForm.Action===1) {
            this.Schedule('新增成功')
          }else if(this.ruleForm.Action===2){
            this.Schedule('修改成功')
          }
        }
      })
    },
    closeDialog() {
        // 重置表单
        this.cloneOnce = [];
        this.cloneloop = [];
        this.$nextTick(() => {
          this.$refs['ruleForm'].resetFields();
        });
        this.ruleForm = Object.assign(this.$data.ruleForm, this.$options.data().ruleForm)
    },
    dateRuleClose(){
      this.$nextTick(() => {
        this.dateForm.Start = '00:00:00';
        this.dateForm.End = '23:59:59';
        this.dateForm.Start2 = this.getNowDate() + ' ' + '00:00:00'
        this.dateForm.End2 = this.getNowDate() + ' ' + '23:59:59'
        // this.$refs['dateForm'].resetFields();
      });
    },
    handleDelete(row){
      this.ruleForm.Action = 3;
      this.ruleForm.Detail = deepClone(row);
      this.$confirm('此操作将永久删除该对象, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.Schedule('删除成功')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    }
  }
};
</script>
<style scoped lang='scss'>
/* @import url(); 引入css类 */
.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
::v-deep.el-input--small{
    width:70% !important;
}
.el-select{
  width: 70% !important;
}
</style>